import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:example/utils/get_ext.dart';
import '../utils/common.dart';

/// 页面基类
abstract class BasePageWidget extends StatelessWidget with BasePageAction {
  BasePageWidget({Key? key, bool doubleTapExit = false}) : super(key: key) {
    this.doubleTapExit.value = doubleTapExit;
  }

  @override
  Widget build(BuildContext context) {
    return _defaultConfig(context);
  }
}

abstract class BasePageState<T extends StatefulWidget> extends State<T>
    with BasePageAction, WidgetsBindingObserver {
  BasePageState({bool doubleTapExit = false}) {
    this.doubleTapExit.value = doubleTapExit;
  }

  @override
  Widget build(BuildContext context) {
    return _defaultConfig(context);
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    hideLoading();
    super.dispose();
  }
}

mixin BasePageAction {
  final RxBool isTap = RxBool(false);
  final RxBool doubleTapExit = RxBool(false);

  Widget _defaultConfig(BuildContext context) {
    _changeFrameDraw(context);
    _changeTheme();

    return _doubleTapExit(
      // 屏幕改变适配
      child: LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
          return _tapHideSoftKeyboard(
            context,
            child: initView(context),
          );
        },
      ),
    );
  }

  /// 软键盘事件和水印
  void _changeFrameDraw(BuildContext context) {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      // double? softInputHeight = MediaQuery.maybeOf(context)?.viewInsets.bottom;
      // if (softInputHeight == null || softInputHeight == 0) {
      //   //关闭键盘
      //   onHideSoftInput();
      // } else {
      //   //显示键盘
      //   onShowSoftInput(softInputHeight);
      // }

      String name = Get.currentRoute;

      // 横屏
      if (Get.parseParams<bool>("isLandscape") == true) {
        if (Platform.isAndroid) {
          SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
              overlays: [SystemUiOverlay.bottom]);

          SystemChrome.setPreferredOrientations([
            DeviceOrientation.landscapeLeft,
            DeviceOrientation.landscapeRight,
          ]);
        } else {
          SystemChrome.setPreferredOrientations([
            DeviceOrientation.landscapeRight,
            DeviceOrientation.landscapeLeft,
          ]);
        }
      }
    });
  }

  /// 页面主题样式
  void _changeTheme() {
    bool isLight = Get.parseParams<bool>("isDark") == false;
    SystemUiOverlayStyle systemUiOverlayStyle = SystemUiOverlayStyle(
      statusBarIconBrightness: isLight ? Brightness.light : Brightness.dark,
      statusBarBrightness: isLight ? Brightness.dark : Brightness.light,
    );
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
  }

  /// 双击退出
  Widget _doubleTapExit({required Widget child}) {
    if (doubleTapExit.value) {
      return WillPopScope(
        onWillPop: () async {
          if (!isTap.value) {
            isTap.value = true;
            showToast("再按一次退出程序");
            Future.delayed(const Duration(seconds: 3), () {
              isTap.value = false;
            });
            return false;
          }
          // onBackPressed.call();
          // exit(0);
          SystemNavigator.pop();
          return true;
        },
        child: child,
      );
    } else {
      return child;
    }
  }

  /// 点击关闭软键盘
  Widget _tapHideSoftKeyboard(BuildContext context, {required Widget child}) {
    return GestureDetector(
      onTap: () {
        FocusScopeNode currentFocus = FocusScope.of(context);
        if (!currentFocus.hasPrimaryFocus &&
            currentFocus.focusedChild != null) {
          hideKeyboard();
        }
      },
      child: child,
    );
  }

  Widget initView(BuildContext context);

  /// 显示软键盘回调
  onShowSoftInput(double softInputHeight) {}

  /// 隐藏软键盘回调
  onHideSoftInput() {}

  /// 双击返回回调
  onBackPressed() {}
}

